<script setup lang="ts">
import type { Dept } from '#/api';

import { onMounted, ref } from 'vue';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  message,
  Modal,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';
import {
  ChevronDown,
  ChevronRight,
  Edit,
  Plus,
  RefreshCw,
  Trash2,
} from 'lucide-vue-next';

import { deleteDeptApi, getDeptTreeApi } from '#/api';

import DeptFormModal from './dept-form-modal.vue';

// 弹窗
const modalVisible = ref(false);
const currentDept = ref<Dept | undefined>();
const parentDeptForAdd = ref<Dept | undefined>();

// 展开/收起状态
const isAllExpanded = ref(true);

// 使用 vxe-table
const [Grid, gridApi] = useVbenVxeGrid<Dept>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: false, // 禁用分页
    },
    treeConfig: {
      transform: false,
      rowField: 'id',
      childrenField: 'children',
      expandAll: true,
      reserve: true,
    },
    columns: [
      {
        field: 'deptName',
        title: '部门名称',
        minWidth: 200,
        treeNode: true,
      },
      {
        field: 'deptCode',
        title: '部门编码',
        minWidth: 150,
      },
      {
        field: 'leaderName',
        title: '部门领导',
        width: 120,
        slots: { default: 'leaderName' },
      },
      {
        field: 'phone',
        title: '联系电话',
        width: 130,
      },
      {
        field: 'email',
        title: '邮箱',
        minWidth: 180,
      },
      {
        field: 'sort',
        title: '排序',
        width: 80,
        align: 'center',
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        align: 'center',
        slots: { default: 'status' },
      },
      {
        field: 'createTime',
        title: '创建时间',
        width: 180,
        slots: { default: 'createTime' },
      },
      {
        field: 'action',
        title: '操作',
        width: 240,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 保存展开状态
function saveExpandedState(): number[] {
  const $grid = gridApi.grid;
  if (!$grid) return [];

  const expandedRows = $grid.getTreeExpandRecords();
  return expandedRows.map((row: any) => row.id);
}

// 恢复展开状态
function restoreExpandedState(expandedIds: number[]) {
  const $grid = gridApi.grid;
  if (!$grid) return;

  setTimeout(() => {
    const allRows = $grid.getTableData().fullData;
    allRows.forEach((row: any) => {
      if (expandedIds.includes(row.id)) {
        $grid.setTreeExpand(row, true);
      }
    });
  }, 100);
}

// 查询部门列表
async function fetchDeptList(keepExpandState = false) {
  const expandedIds = keepExpandState ? saveExpandedState() : [];

  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getDeptTreeApi();
    gridApi.setState({
      gridOptions: {
        data: data || [],
        loading: false,
      },
    });

    if (keepExpandState && expandedIds.length > 0) {
      restoreExpandedState(expandedIds);
    }
  } catch (error: any) {
    message.error(error?.msg || '获取部门列表失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 刷新
function handleRefresh() {
  fetchDeptList(true);
}

// 新增
function handleAdd() {
  currentDept.value = undefined;
  parentDeptForAdd.value = undefined;
  modalVisible.value = true;
}

// 新增子部门
function handleAddChild(record: Dept) {
  currentDept.value = undefined;
  parentDeptForAdd.value = record;
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: Dept) {
  currentDept.value = { ...record };
  parentDeptForAdd.value = undefined;
  modalVisible.value = true;
}

// 删除
function handleDelete(record: Dept) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除部门"${record.deptName}"吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await deleteDeptApi(record.id!);
        message.success('删除成功');
        fetchDeptList(true);
      } catch (error: any) {
        message.error(error?.msg || '删除失败');
      }
    },
  });
}

// 全部展开
function handleExpandAll() {
  const $grid = gridApi.grid;
  if (!$grid) return;

  $grid.setAllTreeExpand(true);
  isAllExpanded.value = true;
}

// 全部收起
function handleCollapseAll() {
  const $grid = gridApi.grid;
  if (!$grid) return;

  $grid.clearTreeExpand();
  isAllExpanded.value = false;
}

// 初始化
onMounted(() => {
  fetchDeptList();
});
</script>

<template>
  <div class="flex h-full flex-col p-4">
    <!-- 表格 -->
    <Card :bordered="false" class="flex flex-1 flex-col overflow-hidden">
      <div class="mb-4 flex flex-shrink-0 justify-between">
        <Space>
          <Button v-permission="'sys:dept:add'" type="primary" @click="handleAdd">
            <Plus :size="16" class="mr-1" />
            新增部门
          </Button>
          <Button @click="handleExpandAll">
            <ChevronDown :size="16" class="mr-1" />
            全部展开
          </Button>
          <Button @click="handleCollapseAll">
            <ChevronRight :size="16" class="mr-1" />
            全部收起
          </Button>
        </Space>
        <Tooltip title="刷新">
          <Button @click="handleRefresh">
            <RefreshCw :size="16" />
          </Button>
        </Tooltip>
      </div>

      <div class="flex-1 overflow-hidden">
        <Grid class="h-full">
          <!-- 部门领导列 -->
          <template #leaderName="{ row }">
            <span>{{ row.leaderName || '-' }}</span>
          </template>

          <!-- 状态列 -->
          <template #status="{ row }">
            <Tag v-if="row.status === 1" color="success">正常</Tag>
            <Tag v-else color="error">停用</Tag>
          </template>

          <!-- 创建时间列 -->
          <template #createTime="{ row }">
            <span>{{ row.createTime || '-' }}</span>
          </template>

          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'sys:dept:add'"
                type="link"
                size="small"
                @click="handleAddChild(row)"
              >
                <Plus :size="14" class="mr-1" />
                新增
              </Button>
              <Button
                v-permission="'sys:dept:edit'"
                type="link"
                size="small"
                @click="handleEdit(row)"
              >
                <Edit :size="14" class="mr-1" />
                编辑
              </Button>
              <Button
                v-permission="'sys:dept:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                <Trash2 :size="14" class="mr-1" />
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <DeptFormModal
      v-model:visible="modalVisible"
      :dept-data="currentDept"
      :parent-dept="parentDeptForAdd"
      @success="() => fetchDeptList(true)"
    />
  </div>
</template>

<style scoped>
:deep(.ant-btn-link) {
  height: auto;
  padding: 0;
}
</style>

